package logic

import (
	"context"
	"errors"
	"user_srv/models/mysql"
	"user_srv/models/redis"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	code := in.SmsCode

	get := redis.Rdb.Get("sendSmslogin" + in.Mobile)

	if get.Val() != code {
		return nil, errors.New("短信验证码有误")
	}

	u := mysql.User{}
	err := u.GetUserMobile(in.Mobile)
	if err != nil {
		return nil, errors.New("查询手机号失败")
	}
	if u.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if u.Password != in.Password {
		return nil, errors.New("密码错误")
	}
	return &user.UserLoginResponse{Id: int32(u.ID)}, nil
}
